package dk.pun.dums.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

import dk.pun.dums.client.presenter.MainPresenter;
import dk.pun.dums.client.presenter.SplashPresenter;
import dk.pun.dums.client.view.MainView;
import dk.pun.dums.client.view.MainViewImpl;
import dk.pun.dums.client.view.SplashViewImpl;
import dk.pun.dums.shared.user.LoginInfo;

public class DUMS implements EntryPoint {

	public void onModuleLoad() {
		final DUMSServiceAsync service = GWT.create(DUMSService.class);
		if (AnonymousLogin.isLoggedIn()) {
			service.anonymousLogin(new AsyncCallback<LoginInfo>() {
				
				@Override
				public void onFailure(final Throwable caught) {
					Window.alert("Failed to login anonymously: " + caught.getMessage());
					GWT.log("Failed to login anonymously: ", caught);
				}

				@Override
				public void onSuccess(final LoginInfo result) {
					loadController(service, result);
				}						
			});
		} else {
			service.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {
				
				@Override
				public void onFailure(final Throwable caught) {
					Window.alert("Failed to login: " + caught.getMessage());
					GWT.log("Failed to login: ", caught);
				}
				
				@Override
				public void onSuccess(final LoginInfo result) {
					if (result.isLoggedIn()) {
						loadController(service, result);
					} else {
						loadLogin(result);
					}
				}
			});
		}
	}
	
	private void loadController(final DUMSServiceAsync service, final LoginInfo loginInfo) {
		final MainView view = new MainViewImpl();
		final MainPresenter presenter = new MainPresenter(view, service, loginInfo);
		presenter.go(RootPanel.get());
	}

	private void loadLogin(final LoginInfo loginInfo) {
		final SplashViewImpl view = new SplashViewImpl();
		final SplashPresenter presenter = new SplashPresenter(view, loginInfo.getLoginURL());
		presenter.go(RootPanel.get());
	}
}
